package com.heima.article.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleConfigService;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author nan
 * @since 2024-06-26
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private IApArticleConfigService configService;

    private static final int MAX_PAGE_SIZE = 100;

    /**
     * 文章加载
     *
     * @param dto
     * @param type
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {

        Integer size = dto.getSize();
        size = (size == null || size == 0) ? 10 : size;
        dto.setSize(Math.min(size, MAX_PAGE_SIZE));

        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }

        List<ApArticle> list = apArticleMapper.load(dto, type);
        return ResponseResult.okResult(list);
    }

    /**
     * 同步审核通过的自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult syncFromNews(ArticleDto dto) {
        //新增文章信息
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);
        save(article);
        //新增文章配置
        ApArticleConfig articleConfig = new ApArticleConfig();
        articleConfig.setArticleId(article.getId());
        articleConfig.setIsComment((short) 1);
        articleConfig.setIsForward((short) 1);
        articleConfig.setIsDown((short) 0);
        articleConfig.setIsDelete((short) 0);
        configService.save(articleConfig);
        //新增文章内容
        ApArticleContent articleContent = new ApArticleContent();
        articleContent.setArticleId(article.getId());
        articleContent.setContent(dto.getContent());
        contentService.save(articleContent);

        return ResponseResult.okResult(article.getId());
    }
}
